package com.example.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.exception.ServiceException;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Jwt拦截器，用于验证JWT令牌是否存在及是否合法
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //不是登录请求，进行权限校验
        String token = request.getHeader("token");
        //判断请求头是否有token
        if (StrUtil.isBlank(token)) {
            //如果为空则查询url路径参数
            token = request.getParameter("token");
        }
        //判断url路径是否有token
        if (StrUtil.isBlank(token)) {
            //两种方式都没有token，抛出业务异常
            throw new ServiceException(401, "请登录");
        }

        //含有token进行校验
        String userId;
        try {
            //解码token获取用户id
            userId = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            throw new ServiceException(401, "请登录");
        }

        //判断用户是否存在及token是否合法
        User user = userService.getById(Integer.valueOf(userId));
        if (user == null) {
            throw new ServiceException(401, "请登录");
        }

        //用户密码加签验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            //进行最终验证
            jwtVerifier.verify(token);
        } catch (Exception e) {
            throw new ServiceException(401, "请登录");
        }

        return true;
    }
}
